package com.dawn.module.hospital.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.util.http.HttpUtils;
import com.dawn.module.hospital.config.CDBPayConfig;
import com.dawn.module.hospital.controller.admin.statics.vo.*;
import com.dawn.module.hospital.controller.app.order.vo.BillQueryReqVO;
import com.dawn.module.hospital.enums.BHConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/19 16:31
 */
@Service
@Slf4j
public class StaticsService extends BHService {

    @Autowired
    private CDBPayConfig payConfig;

    public CommonResult patientCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("beginTime",reqVO.getBeginTime());
        requestBody.put("endTime",reqVO.getEndTime());
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("beginTime",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("endTime",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_PATIENT_COUNT_DAY.getValue(),requestBody);
        return httpResult;
    }

    public CommonResult registerCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("beginTime",reqVO.getBeginTime());
        requestBody.put("endTime",reqVO.getEndTime());
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("beginDate",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("endDate",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_REGISTER_COUNT_DAY.getValue(),requestBody);
        return httpResult;
    }

    public CommonResult billCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("beginTime",reqVO.getBeginTime());
        requestBody.put("endTime",reqVO.getEndTime());
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("beginDate",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("endDate",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_BILL_COUNT_DAY.getValue(),requestBody);
        return httpResult;
    }

    public CommonResult inHospitalCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("beginTime",reqVO.getBeginTime());
        requestBody.put("endTime",reqVO.getEndTime());
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("beginDate",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("endDate",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        }
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_INHOSPITAL_COUNT_DAY.getValue(),requestBody);
        return httpResult;
    }

    public PageResult<PatientRespVO> getPatientPage(SearchReqVO pageReqVO) {
        Map<String, Object> requestBody = buildRequestBody(pageReqVO);
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_PATIENT_PAGE.getValue(),requestBody);
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<PatientRespVO> patientRespVOList = JSON.parseArray(list.toJSONString(), PatientRespVO.class);
            return new PageResult(patientRespVOList,data.getLongValue("total"));
        }
        return null;
    }

    public PageResult<RegisterRespVO> getRegisterPage(SearchReqVO pageReqVO) {
        Map<String, Object> requestBody = buildRequestBody(pageReqVO);
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_REGISTER_PAGE.getValue(),requestBody);
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<RegisterRespVO> registerRespVOS = JSON.parseArray(list.toJSONString(), RegisterRespVO.class);
            return new PageResult(registerRespVOS,data.getLongValue("total"));
        }
       return null;
    }

    private Map<String, Object> buildRequestBody(SearchReqVO pageReqVO) {

        Map<String, Object> requestBody = new HashMap<>();

        String paramStr = JSON.toJSONString(pageReqVO);
        JSONObject jsonObject = JSON.parseObject(paramStr);

        jsonObject.forEach((k,v) -> {
            if(!k.equals("t") && !k.equals("pageNo") && !k.equals("pageSize") && !StringUtils.isEmpty(v)) {
                requestBody.put(k,v);
            }
        });

        requestBody.put("curPage", pageReqVO.getPageNo());
        requestBody.put("pageSize",pageReqVO.getPageSize());

        return requestBody;
    }

    public PageResult<BillRespVO> getBillPage(SearchReqVO pageReqVO) {
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_BILL_PAGE.getValue(),buildRequestBody(pageReqVO));
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<BillRespVO> outpatientRespVOS = JSON.parseArray(list.toJSONString(), BillRespVO.class);
            return new PageResult(outpatientRespVOS,data.getLongValue("total"));
        }
        return null;
    }


    public PageResult<OutpatientRespVO> getOutpatientPage(SearchReqVO pageReqVO) {
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_OUTPATIENT_PAGE.getValue(),buildRequestBody(pageReqVO));
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<OutpatientRespVO> outpatientRespVOS = JSON.parseArray(list.toJSONString(), OutpatientRespVO.class);
            return new PageResult(outpatientRespVOS,data.getLongValue("total"));
        }
        return null;
    }

    public CommonResult getPriceList(String orderNumber){
        Map queryMap = new HashMap();
        queryMap.put("orderNumber",orderNumber);

        CommonResult resultPrice = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_OUTPATIENT_ORDER_PRICES.getValue(), queryMap);
        if (resultPrice.isSuccess()){
            return resultPrice;
        }

        return null;
    }

    public PageResult<OutpatientQrResp> getOutpatientQrPage(SearchReqVO pageReqVO) {
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_OUTPATIENT_QR_PAGE.getValue(),buildRequestBody(pageReqVO));
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<OutpatientQrResp> outpatientRespVOS = JSON.parseArray(list.toJSONString(), OutpatientQrResp.class);
            return new PageResult(outpatientRespVOS,data.getLongValue("total"));
        }
        return null;
    }

    public PageResult<InhospitalRespVO> getInhospitalPage(SearchReqVO pageReqVO) {
        CommonResult httpResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_GET_INHOSPITAL_PAGE.getValue(),buildRequestBody(pageReqVO));
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            JSONArray list = data.getJSONArray("list");
            List<InhospitalRespVO> inhospitalRespVOS = JSON.parseArray(list.toJSONString(), InhospitalRespVO.class);
            return new PageResult(inhospitalRespVOS,data.getLongValue("total"));
        }
        return null;
    }

    public JSONObject billQuery(BillReqVO billReqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",billReqVO.getMchNo());
        if (billReqVO.getSearchTime() != null && billReqVO.getSearchTime().length > 1) {
            LocalDateTime beginDateTime = billReqVO.getSearchTime()[0];
            LocalDateTime endDateTime = billReqVO.getSearchTime()[1];
            requestBody.put("createdStart",LocalDateTimeUtil.formatNormal(beginDateTime));
            requestBody.put("createdEnd",LocalDateTimeUtil.formatNormal(endDateTime));
        }
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_BILL.getValue();
        CommonResult httpResult = HttpUtils.postForm(url,requestBody);
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            return data;
        }
        return null;
    }

    public JSONObject mineBill(BillQueryReqVO billReqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("channelUser",billReqVO.getUserId());
        if (billReqVO.getSearchTime() != null && billReqVO.getSearchTime().length > 1) {
            LocalDateTime beginDateTime = billReqVO.getSearchTime()[0];
            LocalDateTime endDateTime = billReqVO.getSearchTime()[1];
            requestBody.put("createdStart",LocalDateTimeUtil.formatNormal(beginDateTime));
            requestBody.put("createdEnd",LocalDateTimeUtil.formatNormal(endDateTime));
        }
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_BILL.getValue();
        CommonResult httpResult = HttpUtils.postForm(url,requestBody);
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            return data;
        }
        return null;
    }


    public HashMap payAmountWeek() {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",null);
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_PAY_AMOUNT_WEEK.getValue();
        CommonResult commonResult = HttpUtils.postForm(url,requestBody);
        if(commonResult.getCode() == 0) {
            HashMap resultMap = JSON.parseObject(commonResult.getData().toString(),HashMap.class);
            return resultMap;
        }
        return null;
    }

    public HashMap numCount() {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",null);
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_NUM_COUNT.getValue();
        CommonResult commonResult = HttpUtils.postForm(url,requestBody);
        if(commonResult.getCode() == 0) {
            HashMap resultMap = JSON.parseObject(commonResult.getData().toString(),HashMap.class);
            return resultMap;
        }
        return null;
    }

    public CommonResult payCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",null);
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("createdStart",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("createdEnd",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd"));
        }
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_PAY_COUNT.getValue();
        CommonResult commonResult = HttpUtils.postForm(url,requestBody);
        if(commonResult.getCode() == 0) {
            List<HashMap> list = JSON.parseArray(commonResult.getData().toString(),HashMap.class);


        if(list != null && list.size() > 0) {
            Set<String> category = new LinkedHashSet<>();
            HashMap<String,LinkedList> series = new HashMap<>();
            list.forEach( l -> {
                String date = l.get("date").toString();
                String type = l.get("type").toString();
                BigDecimal payAmount = new BigDecimal(l.get("payAmount").toString());
                category.add(date);
                LinkedList serie;
                if(series.containsKey(type)) {
                    serie = series.get(type);
                } else {
                    serie = new LinkedList<>();
                }
                serie.add(payAmount);
                series.put(type,serie);
            });
            HashMap<String,Object> resultData = new HashMap();
            resultData.put("category",category);
            resultData.put("series",series);
            return CommonResult.success(resultData);
        }
        }
        return null;
    }

    public CommonResult payTypeCount(TradeOrderTrendReqVO reqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",null);
        if (!StringUtils.isEmpty(reqVO.getBeginTime())) {
            requestBody.put("createdStart",LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd"));
        }
        if (!StringUtils.isEmpty(reqVO.getEndTime())) {
            requestBody.put("createdEnd",LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd"));
        }
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_PAY_TYPE_COUNT.getValue();
        CommonResult commonResult = HttpUtils.postForm(url,requestBody);
        return commonResult;
    }

    public JSONObject chsBillQuery(BillReqVO billReqVO) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mchNo",billReqVO.getMchNo());
        if (billReqVO.getSearchTime() != null && billReqVO.getSearchTime().length > 1) {
            LocalDateTime beginDateTime = billReqVO.getSearchTime()[0];
            LocalDateTime endDateTime = billReqVO.getSearchTime()[1];
            requestBody.put("createdStart",LocalDateTimeUtil.formatNormal(beginDateTime));
            requestBody.put("createdEnd",LocalDateTimeUtil.formatNormal(endDateTime));
        }
        String url = payConfig.getUrl() + BHConstants.QUERY_CDB_CHS_BILL.getValue();
        CommonResult httpResult = HttpUtils.postForm(url,requestBody);
        if(httpResult.isSuccess()) {
            JSONObject data = (JSONObject)httpResult.getData();
            return data;
        }
        return null;
    }
}
